Skip to content

Latest commit

 

History

History
48 lines (40 loc) · 1.62 KB

File metadata and controls

48 lines (40 loc) · 1.62 KB
title description canonical status lastmod
The Fluent API HasForeignKey Method
Usage of the Fluent API HasForeignKey Method in Entity Framework Core
/configuration/fluent-api/hasforeignkey-method
Published
2023-02-27

EF Core HasForeignKey

The Entity Framework Core Fluent API HasForeignKey method is used to specify which property is the foreign key in a relationship.

In the following example, the AuthorFK property in the Book entity does not follow Entity Framework Core's convention for foreign key names. Left as it is, Entity Framework Core will create an AuthorFK field and an AuthorId field which it will configure as a foreign key:

public class Author
{
    public int AuthorId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public ICollection<Book> Books { get; set; }
}

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public int AuthorFK { get; set; }
    public Author Author { get; set; }
}

The AuthorFK property is configured as the foreign key in the OnModelCreating method:

public class SampleContext : DbContext
{
    public DbSet<Author> Authors { get; set; }
    public DbSet<Book> Books { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Book>()
            .HasForeignKey(p => p.AuthorFK);
    }

Data Annotations

The data annotations equivalent to the HasForeignKey method is the ForeignKey attribute.